var prefix = jsctx + "/acctTenantOperator";

function listAcctRuleRepository(ruleType,loadType) {
    //获取规则模板
    var operatorStationId = $("#operatorStationId").val();
    var acctRuleId = $("#acctRuleId").val();
    var ruleName='';
    if (ruleType == '0'){
        ruleName=$("#elecRuleName").val();
    }else if(ruleType == '1'){
        ruleName=$("#serviceRuleName").val();
    }else{
        ruleName=$("#gkdRuleName").val();
    }
    // alert(operatorStationId)
    $.ajax({
        "type": "POST",
        "url": prefix + "/listAcctRuleRepository",
        "data": {
            "operatorStationId": operatorStationId,
            "acctRuleId":acctRuleId,
            "ruleName":ruleName
        },
        "success": function (data) {
            $(".elecRuleLiBrary .acctRuleWrap").html("");
            $(".elecRuleLiBrary .elecRuleBtnWrap").html("");
            $(".serviceRuleLiBrary .acctRuleWrap").html("");
            $(".serviceRuleLiBrary .elecRuleBtnWrap").html("");
            $(".gkdRuleLiBrary .acctRuleWrap").html("");
            $(".gkdRuleLiBrary .elecRuleBtnWrap").html("");
            console.log(data)
            if (data.status == 200) {
                if(loadType!="2"){
                    if (data.data.elecAcctRule) {
                        filterRule(data.data.elecAcctRule, "elecAcctRule", '');//电费回显
                    }
                    if (data.data.serviceAcctRule) {
                        filterRule(data.data.serviceAcctRule, "serviceAcctRule", '');//服务费费回显
                    }
                    if (data.data.acctSubItem && data.data.acctSubItem.length>0) {
                        for (var i = 0; i < data.data.acctSubItem.length; i++) {//子项回显
                            var item = data.data.acctSubItem[i];
                            for (var x in item) {
                                var ruleName = x.split("_")[0];
                                // var id = x.split("_")[1];
                                filterRule(item[x], 'acctSubItem', ruleName)
                            }
                        }
                    }
                }
                for (var i = 0; i < data.data.acctSubItemRepository.length; i++) {//自定义模板库
                    var item = data.data.acctSubItemRepository[i];
                    for (var x in item) {
                        var ruleName = x.split("_")[0];
                        var id = x.split("_")[1];
                        filterRule(item[x], 'acctSubItemRepository', ruleName, id)
                    }
                }
                for (var i = 0; i < data.data.elecAcctRuleRepository.length; i++) {//电费模板库
                    var item = data.data.elecAcctRuleRepository[i];
                    for (var x in item) {
                        var ruleName = x.split("_")[0];
                        var id = x.split("_")[1];
                        filterRule(item[x], 'elecAcctRuleRepository', ruleName,id)
                    }
                }
                for (var i = 0; i < data.data.serviceAcctRuleRepository.length; i++) {//服务费模板库
                    var item = data.data.serviceAcctRuleRepository[i];
                    for (var x in item) {
                        var ruleName = x.split("_")[0];
                        var id = x.split("_")[1];
                        filterRule(item[x], 'serviceAcctRuleRepository',ruleName,id)
                    }
                }
            } else {
                layer.msg("操作失败");
            }
        }
    })
    var copyBtnIndex = 1;
    var elecRuleListIndex = 1;
    var serviceRuleListIndex = 1;
    var gkdRuleListIndex = 1;
    var eleId = 4;
    function filterRule(arr, ruleType, ruleName,id) {
        if (arr.length == 0) {
            return
        }
        if(ruleType=="acctSubItem"){
            var model_one = arr[0];
            var model_two = '';
            switch (arr[1]) {
                case 'a':
                    model_two = "平台服务费";
                    break;
                case 'b':
                    model_two = "平台电费";
                    break;
                case 'c':
                    model_two = "平台总金额";
                    break;
                case 'd':
                    model_two = "平台优惠金额";
                    break;
                case 'e':
                    model_two = "平台实收金额";
                    break;
                case 'f':
                    model_two = "平台电量";
                    break;
                case 'g':
                    model_two = "咨询订单金额";
                    break;
                default: model_two = arr[1]
            }
            console.log(model_two)
        }
        var patt1 = /[a-z]/;
        var patt2 = /^[+-]?(0|([1-9]\d*))(\.\d+)?$/g;
        var ruleBtn = '';
        var ruleContent = '';
        for (var i = 0; i < arr.length; i++) {
            if (patt1.test(arr[i])) {
                var buttonName;
                switch (arr[i]) {
                    case 'a':
                        buttonName = "平台服务费";
                        break;
                    case 'b':
                        buttonName = "平台电费";
                        break;
                    case 'c':
                        buttonName = "平台总金额";
                        break;
                    case 'd':
                        buttonName = "平台优惠金额";
                        break;
                    case 'e':
                        buttonName = "平台实收金额";
                        break;
                    case 'f':
                        buttonName = "平台电量";
                        break;
                    case 'g':
                        buttonName = "咨询订单金额";
                        break;
                }
                ruleBtn += "<button id='copy" + (copyBtnIndex + 1) + "' class='btn btn-lg copyBtn btn-default variable' draggable='true' ondragstart='drag(event)'>" + buttonName + "</button>"
                ruleContent += buttonName;
            } else if (patt2.test(arr[i])) {
                ruleBtn += "<button id='copy" + (copyBtnIndex + 1) + "' class='btn btn-lg copyBtn btn-default amountInputBlock' style='width:auto;padding: 0;' draggable='true' ondragstart='drag(event)'>" +
                    "<input type='input' value='" + arr[i] + "' class='amountInput'  onkeyup='clearNoNum(this)' placeholder='自定义数值' >" +
                    "</button>"
                ruleContent += arr[i];
            } else {
                ruleBtn += "<button id='copy" + (copyBtnIndex + 1) + "' class='btn btn-lg copyBtn btn-default symbol' draggable='true' ondragstart='drag(event)'>" + arr[i] + "</button>"
                ruleContent += arr[i];
            }
            copyBtnIndex++;
        }

        //判断交互类型
        if (ruleType == "elecAcctRule") {//
            $("#div2").html(ruleBtn);
            $(".preview1").html("预览：结算电费=" + ruleContent);
            $(".finalRule1").html(ruleContent);
        } else if (ruleType == "serviceAcctRule") {
            $("#div3").html(ruleBtn);
            $(".preview2").html("预览：结算服务费=" + ruleContent);
            $(".finalRule2").html(ruleContent);
        }else if (ruleType == "acctSubItem") {
            if($(".new_model:last").find(".drag_child3").html().indexOf("button")==-1){
                $(".new_model:last").remove()
            }
            // $(".new_model").remove()
            var ruleContent = ruleBtn.substring(ruleBtn.indexOf("=</button>")+10)//找到等号的位置进行截取
            $('.new_label').append(` <div class="new_model" id="newModel"><button class="model_one">${model_one}</button> <input class="model_two" type="text" value="${model_two}"> <span class="model_three">=</span> <div id="div${eleId}" class="drag_child model_f drag_left drag_child3" ondragover="allowDrop(event)" ondrop="drop(event)">${ruleContent}</div><button class="btn input-distance templatesBtn model_six" type="gkd\"> 存入模板</button><button class="model_five delBtn">删除</button></div>`)
            eleId++
            // $(".finalRule3").html(ruleContent);
        }
        else if (ruleType == "elecAcctRuleRepository") {
            ruleBtn = "<div class="+'ruleBtnList'+elecRuleListIndex+">"+ruleBtn+"</div>"
            if (elecRuleListIndex == 1) {
                var str = "<div class='acctRuleList' attrId='"+id+"'>" +
                    "<div class='choiceBox'>" + "<span class='redCircle'>" + "</span>" + "</div>" + "<div class='title'>" + ruleName + "</div>" +
                    "<div class='acctContent'>规则" + elecRuleListIndex + "：结算电费 =<span>" + ruleContent + "</span>" + "</div>" +
                    "</div>"
            } else {
                var str = "<div class='acctRuleList' attrId='"+id+"'>" +
                    "<div class='choiceBox'>" + "<span class='redCircle hide'>" + "</span>" + "</div>" + "<div class='title'>" + ruleName + "</div>" +
                    "<div class='acctContent'>规则" + elecRuleListIndex + "：结算电费 =<span>" + ruleContent + "</span>" + "</div>" +
                    "</div>"
            }
            $(".elecRuleLiBrary .acctRuleWrap").append(str);
            $(".elecRuleLiBrary .elecRuleBtnWrap").append(ruleBtn);
            elecRuleListIndex++;
        } else if (ruleType == "serviceAcctRuleRepository") {
            ruleBtn = "<div class="+'ruleBtnList'+serviceRuleListIndex+">"+ruleBtn+"</div>"
            if (serviceRuleListIndex == 1) {
                var str = "<div class='acctRuleList' attrId='"+id+"'>" +
                    "<div class='choiceBox'>" + "<span class='redCircle'>" + "</span>" + "</div>" + "<div class='title'>" + ruleName + "</div>" +
                    "<div class='acctContent'>规则" + serviceRuleListIndex + "：结算服务费 =<span>" + ruleContent + "</span>" + "</div>" +
                    "</div>"
            } else {
                var str = "<div class='acctRuleList' attrId='"+id+"'>" +
                    "<div class='choiceBox'>" + "<span class='redCircle hide'>" + "</span>" + "</div>" + "<div class='title'>" + ruleName + "</div>" +
                    "<div class='acctContent'>规则" + serviceRuleListIndex + "：结算服务费 =<span>" + ruleContent + "</span>" + "</div>" +
                    "</div>"
            }
            $(".serviceRuleLiBrary .acctRuleWrap").append(str);
            $(".serviceRuleLiBrary .elecRuleBtnWrap").append(ruleBtn);
            serviceRuleListIndex++;
        }
        else if(ruleType == "acctSubItemRepository"){
            ruleBtn = "<div class=" + 'ruleBtnList' + gkdRuleListIndex + ">" + ruleBtn + "</div>"
            if (gkdRuleListIndex == 1) {
                var str = "<div class='acctRuleList' attrId='" + id + "'>" +
                    "<div class='choiceBox'>" + "<span class='redCircle'>" + "</span>" + "</div>" + "<div class='title'>" + ruleName + "</div>" +
                    "<div class='acctContent'>规则" + gkdRuleListIndex + ":<span>" +ruleContent + "</span>" + "</div>" +
                    "</div>"
            } else {
                var str = "<div class='acctRuleList' attrId='" + id + "'>" +
                    "<div class='choiceBox'>" + "<span class='redCircle hide'>" + "</span>" + "</div>" + "<div class='title'>" + ruleName + "</div>" +
                    "<div class='acctContent'>规则" + gkdRuleListIndex + ":<span>" +ruleContent + "</span>" + "</div>" +
                    "</div>"
            }
            $(".gkdRuleLiBrary .acctRuleWrap").append(str);
            $(".gkdRuleLiBrary .elecRuleBtnWrap").append(ruleBtn);
            gkdRuleListIndex++;
        }
    }
}
listAcctRuleRepository()
//允许拖放
function allowDrop(event) {
    event.preventDefault();//默认地，无法将数据/元素放置到其他元素中。如果需要设置允许放置，我们必须阻止对元素的默认处理方式
}

//拖放
function drag(event) {
    console.log($(this))
    event.dataTransfer.setData("Text", event.target.id);
    event.dataTransfer.setData("first01", event.target.parentElement.parentElement.parentElement.id);   //获取第一个div的id
    event.dataTransfer.setData("first02", event.target.parentElement.parentElement.id);   //左侧第一个div的id
    event.dataTransfer.setData("buttonId", event.target.parentElement.parentElement.firstChild.id);   //获取第一个div的button的id

}

var count = 1;
var map = {};
var dragId = 4;

//放置数据
function drop(event) {
    // console.log(event)
    event.preventDefault();
    event.stopPropagation();
    var data = event.dataTransfer.getData("Text");//copy按钮的id
    var first01 = event.dataTransfer.getData("first01");
    var first02 = event.dataTransfer.getData("first02");
    var buttonId = event.dataTransfer.getData("buttonId");
    if (first01 == 'div1' && event.target.id != 'div1' && event.target.id.substring(0, 4) != 'copy' && event.target.id.substring(0, 4) != 'drag') {
        // if (event.target.childNodes.length == 0) {
        var idVO = "button" + count;
        document.getElementById(event.target.id).apendChild = '<button id=' + idVO + ' class="btn btn-xs btn-default img_del" onclick="del(this)"><span class="fa fa-close"></span></button>';
        var item = document.getElementById(data).cloneNode(true);
        item.id = "copy" + count;    //设置copy对象的id)
        if (event.target.id == "div2") {
            if ($("#div2 .copyBtn").length > 0) {
                var beforeEle = '';
                var afterEle = '';
                var flag = true;
                $("#div2 .copyBtn").each(function () {
                    if(flag){
                        var x = $(this).offset().left;
                        var y = $(this).offset().top;
                        if (event.clientX < x && event.clientY > y && event.clientY < y + $(this).height()) {
                            afterEle = $(this);
                            flag = false
                        } else if (event.clientX > x && event.clientY > y && event.clientY < y + $(this).height()) {
                            beforeEle = $(this);
                        }
                    }

                })
                if (beforeEle) {
                    beforeEle.after($(item));
                } else {
                    afterEle.before($(item));
                }
                console.log(beforeEle);
                console.log(afterEle);
            } else {
                event.target.appendChild(item);
            }
        } else if(event.target.id == "div3"){
            if ($("#div3 .copyBtn").length > 0) {
                var beforeEle = '';
                var afterEle = '';
                var flag = true;
                $("#div3 .copyBtn").each(function () {
                    if(flag){
                        var x = $(this).offset().left;
                        var y = $(this).offset().top;
                        if (event.clientX < x && event.clientY > y && event.clientY < y + $(this).height()) {
                            afterEle = $(this);
                            flag = false
                        } else if (event.clientX > x && event.clientY > y && event.clientY < y + $(this).height()) {
                            beforeEle = $(this);
                        }
                    }

                })
                console.error($(item))
                if (beforeEle) {
                    beforeEle.after($(item));
                } else {
                    afterEle.before($(item));
                }
                console.log(beforeEle);
                console.log(afterEle);
            } else {
                event.target.appendChild(item);
            }
        }else{
            var targetId = event.target.id;
            if ($(`#${targetId} .copyBtn`).length > 0) {
                var beforeEle = '';
                var afterEle = '';
                var flag = true;
                $(`#${targetId} .copyBtn`).each(function () {
                    if(flag){
                        var x = $(this).offset().left;
                        var y = $(this).offset().top;
                        if (event.clientX < x && event.clientY > y && event.clientY < y + $(this).height()) {
                            afterEle = $(this);
                            flag = false
                        } else if (event.clientX > x && event.clientY > y && event.clientY < y + $(this).height()) {
                            beforeEle = $(this);
                        }
                    }

                })
                if (beforeEle) {
                    beforeEle.after($(item));
                } else {
                    afterEle.before($(item));
                }
                console.log(beforeEle);
                console.log(afterEle);
            } else {
                event.target.appendChild(item);
            }
        }
        document.getElementById(data).draggable = true;     //禁止拖动
        $("#" + item.id).children().css("font-size", "16px");
        // $("#"+item.id).css("padding","40px 16px");
        map[idVO] = data;
        count++;
        //预览
        var testStr1 = '';
        var testStr2 = '';
        var showStr1 = '';
        var showStr2 = '';
        $(".drag_child1 .copyBtn").each(function () {
            if ($(this).hasClass("variable")) {
                testStr1 += "[" + $(this).text() + "]";
                showStr1 += $(this).text();
            } else if ($(this).children().length > 0) {
                testStr1 += Math.abs(parseFloat($(this).children('input').val()));
                showStr1 += "("+$(this).children('input').val()+")";
            } else {
                testStr1 += $(this).text();
                showStr1 += $(this).text();
            }
        })
        $(".drag_child2 .copyBtn").each(function () {
            if ($(this).hasClass("variable")) {
                testStr2 += "[" + $(this).text() + "]";
                showStr2 += $(this).text();
            } else if ($(this).children().length > 0) {
                testStr2 += $(this).children('input').val();
                showStr2 += $(this).children('input').val();
            } else {
                testStr2 += $(this).text();
                showStr2 += $(this).text();
            }
        })
        $(".preview1").html("预览：结算电费=" + showStr1);
        $(".preview2").html("预览：结算服务费=" + showStr2);

    } else if (event.target.id!= 'div1'&& event.target.id.substring(0, 4) != 'copy' && event.target.id.substring(0, 4) != 'drag') {//同盒子内拖拽
        // if (event.target.id != "div2" && event.target.id.substring(0, 4) != 'copy') {
        //     $("#div2 #" + data).remove()
        // }
        // if (event.target.id != "div3" && event.target.id.substring(0, 4) != 'copy') {
        //     $("#div3 #" + data).remove()
        // }
        if (event.target.id != $("#"+data).parents(".drag_child").attr("id") && event.target.id.substring(0, 4) != 'copy') {
            $("#"+data).remove()
        }
        if (event.target.id == "div2") {
            if ($("#div2 .copyBtn").length > 0) {
                var beforeEle = '';
                var afterEle = '';
                var flag = true;
                $("#div2 .copyBtn").each(function () {
                    if(flag){
                        var x = $(this).offset().left;
                        var y = $(this).offset().top;
                        if (event.clientX < x && event.clientY > y && event.clientY < y + $(this).height()) {
                            afterEle = $(this);
                            flag = false
                        } else if (event.clientX > x && event.clientY > y && event.clientY < y + $(this).height()) {
                            beforeEle = $(this);
                        }
                    }

                })
                if (beforeEle) {
                    beforeEle.after($("#" + data));
                } else {
                    afterEle.before($("#" + data));
                }
            }
        } else if(event.target.id == "div3"){
            if ($("#div3 .copyBtn").length > 0) {
                var beforeEle = '';
                var afterEle = '';
                var flag = true;
                $("#div3 .copyBtn").each(function () {
                    if(flag){
                        var x = $(this).offset().left;
                        var y = $(this).offset().top;
                        if (event.clientX < x && event.clientY > y && event.clientY < y + $(this).height()) {
                            afterEle = $(this);
                            flag = false
                        } else if (event.clientX > x && event.clientY > y && event.clientY < y + $(this).height()) {
                            beforeEle = $(this);
                        }
                    }

                })
                if (beforeEle) {
                    beforeEle.after($("#" + data));
                } else {
                    afterEle.before($("#" + data));
                }
            }
        }else{
            var targetId = event.target.id;
            if ($(`#${targetId} .copyBtn`).length > 0) {
                var beforeEle = '';
                var afterEle = '';
                var flag = true;
                $(`#${targetId} .copyBtn`).each(function () {
                    if(flag){
                        var x = $(this).offset().left;
                        var y = $(this).offset().top;
                        if (event.clientX < x && event.clientY > y && event.clientY < y + $(this).height()) {
                            afterEle = $(this);
                            flag = false
                        } else if (event.clientX > x && event.clientY > y && event.clientY < y + $(this).height()) {
                            beforeEle = $(this);
                        }
                    }

                })
                if (beforeEle) {
                    beforeEle.after($("#" + data));
                } else {
                    afterEle.before($("#" + data));
                }
            }
        }
        //预览
        var testStr1 = '';
        var testStr2 = '';
        var showStr1 = '';
        var showStr2 = '';
        $(".drag_child1 .copyBtn").each(function () {
            if ($(this).hasClass("variable")) {
                testStr1 += "[" + $(this).text() + "]";
                showStr1 += $(this).text();
            } else if ($(this).children().length > 0) {
                testStr1 += $(this).children('input').val();
                showStr1 += $(this).children('input').val();
            } else {
                testStr1 += $(this).text();
                showStr1 += $(this).text();
            }
        })
        $(".drag_child2 .copyBtn").each(function () {
            if ($(this).hasClass("variable")) {
                testStr2 += "[" + $(this).text() + "]";
                showStr2 += $(this).text();
            } else if ($(this).children().length > 0) {
                testStr2 += $(this).children('input').val();
                showStr2 += $(this).children('input').val();
            } else {
                testStr2 += $(this).text();
                showStr2 += $(this).text();
            }
        })
        $(".preview1").html("预览：结算电费=" + showStr1);
        $(".preview2").html("预览：结算服务费=" + showStr2);
    }
}

$(".drag_child1").on("blur", ".amountInput", function () {
    //预览
    var testStr1 = '';
    var showStr1 = '';
    $(".drag_child1 .copyBtn").each(function () {
        if ($(this).hasClass("variable")) {
            testStr1 += "[" + $(this).text() + "]"
            showStr1 += $(this).text();
        } else if ($(this).children().length > 0) {
            testStr1 += Math.abs(parseFloat($(this).children('input').val()));
            showStr1 += "("+$(this).children('input').val()+")";
        } else {
            testStr1 += $(this).text();
            showStr1 += $(this).text();
        }
    })
    $(".preview1").html("预览：结算电费=" + showStr1);
})
$(".drag_child2").on("blur", ".amountInput", function () {
    //预览
    var testStr2 = '';
    var showStr2 = '';
    $(".drag_child2 .copyBtn").each(function () {
        if ($(this).hasClass("variable")) {
            testStr2 += "[" + $(this).text() + "]"
            showStr2 += $(this).text();
        } else if ($(this).children().length > 0) {
            testStr2 += $(this).children('input').val();
            showStr2 += $(this).children('input').val();
        } else {
            testStr2 += $(this).text();
            showStr2 += $(this).text();
        }
    })
    $(".preview2").html("预览：结算服务费=" + showStr2);
})
function check(string, showStr, index,modul,resultStr) {
    // 剔除空白符
    string = string.replace(/[\r\n]/g, "").replace(/\ +/g, "");
    var flag = true;
    // 错误情况，空字符串
    if ("" === string) {
        // return false;
    }
    // if (/^[\x\÷\+\-\*\/]/.test(string)) {
    //     flag = false;
    //     console.error("运算符开头");
    // }

    //错误情况，运算符结尾
    if (/[\x\÷\+\-\*\/]$/.test(string)) {
        flag = false;
        console.error("运算符结尾");
    }

    // 错误情况，(后面是运算符或者)
    if (/\([\x\÷\+\-\*\/]/.test(string)) {
        flag = false;
        console.error("(后面是运算符");
    }
    // 错误情况，运算符连续
    if (/[\x\÷\+\-\*\/]{2,}/.test(string)) {
        flag = false;
        console.error("运算符连续");
    }
    // 空括号
    if (/\(\)/.test(string)) {
        flag = false;
        console.error("括号内为空");
    }
    // 错误情况，括号不配对
    var stack = [];
    for (var i = 0, item; i < string.length; i++) {
        item = string.charAt(i);
        if ('(' === item) {
            stack.push('(');
        } else if (')' === item) {
            if (stack.length > 0) {
                stack.pop();
            } else {
                flag = false;
                console.error("括号不匹配");
            }
        }
    }

    if (0 !== stack.length) {
        flag = false;
        console.error("空括号");
    }
    if (/\([\÷\+\-\*\/]/g.test(string)) {
        flag = false;
        console.error("(后面是运算符")
    }
    // 错误情况，)前面是运算符
    if (/[\÷\+\-\*\/]\)/g.test(string)) {
        flag = false;
        console.error(")前面是运算符")
    }
    var pop = string.split().length - 1;
    var editString = string;
    while (i < pop) {
        console.log(editString)
        if (/[\÷\+\-\*\/]\(/g.test(editString)) {
            editString = editString.substring(0, pop + 1);
            i++;
        } else {
            flag = false;
            console.error("(前面不是运算符");
        }

    }
    if (index == 1) {
        $(".drag_child1 .variable").each(function () {
            if ($(this).prev().hasClass("variable") || $(this).next().hasClass("variable") || $(this).prev().hasClass("amountInput") || $(this).next().hasClass("amountInput")) {
                console.error("变量之间没有符号");
                flag = false;
            }
        })
        $(".drag_child1 .amountInputBlock").each(function () {
            if ($(this).prev().hasClass("variable") || $(this).next().hasClass("variable") || $(this).prev().hasClass("amountInputBlock") || $(this).next().hasClass("amountInputBlock")) {
                console.error("变量之间没有符号");
                flag = false;
            }
        })
    } else {
        $(".drag_child2 .variable").each(function () {
            if ($(this).prev().hasClass("variable") || $(this).next().hasClass("variable") || $(this).prev().hasClass("amountInput") || $(this).next().hasClass("amountInput")) {
                console.error("变量之间没有符号");
                flag = false;
            }
        })
        $(".drag_child2 .amountInputBlock").each(function () {
            if ($(this).prev().hasClass("variable") || $(this).next().hasClass("variable") || $(this).prev().hasClass("amountInputBlock") || $(this).next().hasClass("amountInputBlock")) {
                console.error("变量之间没有符号");
                flag = false;
            }
        })
    }
    // // 错误情况，数字后面不是运算符或括号
    if (flag) {
        if (index == 1) {
            $(".preview1").html("预览：结算电费=" + showStr);
            $(".finalRule1").html(resultStr);
            $(".acctRuleModal").attr("type", "elec");
            if(modul=="modul"){
                $(".acctRuleNameModal .ruleName").val("");
                $(".acctRuleNameModal").removeClass("hide").attr("type","elec");
            }
            else if(modul=="save"){

            }else{
                saveAcctRuleRepository(1,'')
            }
        } else if(index==2){
            $(".preview2").html("预览：结算服务费=" + showStr);
            $(".finalRule2").html(resultStr);
            $(".acctRuleModal").attr("type", "service");
            if(modul=="modul"){
                $(".acctRuleNameModal .ruleName").val("");
                $(".acctRuleNameModal").removeClass("hide").attr("type","service");
            }else if(modul=="save"){

            }else{
                saveAcctRuleRepository(2,'')
            }

        }else{

        }
        return true
        // $(".acctRuleModal").removeClass("hide");
    } else {
        alert("结算规则有误，请检查修正");
        return false
    }

}

$(".container-fluid").css("height", $(window).height() - 20);

layui.use('laydate', function () {
    var laydate = layui.laydate;

    //执行一个laydate实例
    var startDate = laydate.render({
        elem: '#ruleStartTime', //指定元素
        type: 'date',
        format: 'yyyy-MM-dd HH:mm:ss',
        trigger: 'click',
        position: 'fixed',
        done:function(value,date){
            //console.log(value); //得到日期生成的值，如：2017-08-18
            //console.log(date); //得到日期时间对象：{year: 2017, month: 8, date: 18, hours: 0, minutes: 0, seconds: 0}
            endDate.config.min={
                year:date.year,
                month:date.month-1,//关键(多了一个月，需要减1)
                date:date.date,
                hours:date.hours,
                minutes:date.minutes,
                seconds:date.seconds
            };
        }
    });
    var endDate = laydate.render({
        elem: '#ruleEndTime', //指定元素
        type: 'date',
        format: 'yyyy-MM-dd HH:mm:ss',
        trigger: 'click',
        position: 'fixed',
        done: function (value, date) {
            startDate.config.max={
                year:date.year,
                month:date.month-1,//关键(多了一个月，需要减1)
                date:date.date,
                hours:date.hours,
                minutes:date.minutes,
                seconds:date.seconds
            };
            var ruleEndTime='';
            if (date.month>=10 && date.date>=10){
                ruleEndTime=date.year+"-"+date.month+"-"+date.date+" 23:59:59";
            } else if (date.month<10 && date.date>=10) {
                ruleEndTime=date.year+"-0"+date.month+"-"+date.date+" 23:59:59";
            } else if (date.month>=10 && date.date<10){
                ruleEndTime=date.year+"-"+date.month+"-0"+date.date+" 23:59:59";
            } else if (date.month<10 && date.date<10){
                ruleEndTime=date.year+"-0"+date.month+"-0"+date.date+" 23:59:59";
            } else {
                $("#ruleEndTime").val("");
            }
            $("#ruleEndTime").val(ruleEndTime);
        }
    });
})

// function hide(ele) {
//     $(ele).parents(".acctModal").addClass("hide");
// }

$(".previewBlock .templatesBtn").click(function () {
    if($(this).attr("type")=="elec"){
        var testStr = '';
        var showStr = '';
        var resultStr = '';
        $(".drag_child1 .copyBtn").each(function () {
            if ($(this).hasClass("variable")) {
                testStr += "[" + $(this).text() + "]"
                showStr += $(this).text();
                resultStr += $(this).text();
            } else if ($(this).children().length > 0) {
                testStr += Math.abs(parseFloat($(this).children('input').val()));
                showStr += "("+$(this).children('input').val()+")";
                resultStr += $(this).children('input').val();
            } else {
                testStr += $(this).text();
                showStr += $(this).text();
                resultStr += $(this).text();
            }
        })
        if (testStr == "") {
            alert("结算规则为空");
            return;
        }
        check(testStr, showStr, 1,'modul',resultStr)
    }else if($(this).attr("type")=="service"){
        var testStr = '';
        var showStr = '';
        var resultStr = '';
        $(".drag_child2 .copyBtn").each(function () {
            if ($(this).hasClass("variable")) {
                testStr += "[" + $(this).text() + "]"
                showStr += $(this).text();
                resultStr += $(this).text();
            } else if ($(this).children().length > 0) {
                testStr += Math.abs(parseFloat($(this).children('input').val()));
                showStr += "("+$(this).children('input').val()+")";
                resultStr += $(this).children('input').val();
            } else {
                testStr += $(this).text();
                showStr += $(this).text();
                resultStr += $(this).text();
            }
        })
        if (testStr == "") {
            alert("结算规则为空");
            return;
        }
        check(testStr, showStr, 2,'modul',resultStr)
    }

})

//重新设置
$(".resetBtn1").click(function () {
    $("#div2").html("");
    $(".preview1").html("预览：结算电费= ")
})
$(".resetBtn2").click(function () {
    $("#div3").html("");
    $(".preview2").html("预览：结算服务费= ")
})

$(".selectMouldBtn").click(function () {
    $(".acctRuleLiBrary").removeClass("hide").attr("type", $(this).attr("type"));
    if ($(this).attr("type") == "elec") {
        $(".elecRuleLiBrary").removeClass("hide");
        $(".serviceRuleLiBrary").addClass("hide");
        $(".gkdRuleLiBrary").addClass("hide");
    } else if($(this).attr("type")=="service"){
        $(".elecRuleLiBrary").addClass("hide");
        $(".serviceRuleLiBrary").removeClass("hide");
        $(".gkdRuleLiBrary").addClass("hide");
    }else{
        $(".elecRuleLiBrary").addClass("hide");
        $(".serviceRuleLiBrary").addClass("hide");
        $(".gkdRuleLiBrary").removeClass("hide");
    }
})
$(".elecRuleLiBrary,.serviceRuleLiBrary").on("click", ".acctRuleList", function () {
    $(this).find(".redCircle").removeClass("hide").parents(".acctRuleList").siblings(".acctRuleList").find(".redCircle").addClass("hide");
})

$(".container-fluid").on("click",".delRuleListBtn",function () {
    $(this).parents(".submitBlock").siblings(".acctRuleWrap").find(".redCircle").each(function (index) {
        if (!$(this).hasClass("hide")) {
            var ruleRepositoryId = $(this).parents(".acctRuleList").attr("attrId");
            $.ajax({
                "type":"POST",
                "url":prefix+"/deleteAcctRuleRepository",
                "data":{
                    ruleRepositoryId:ruleRepositoryId
                },
                "success":function (data) {
                    if(data.status=="200"){
                        layer.msg("删除成功");
                        listAcctRuleRepository('',"2");
                    }else{
                        layer.msg("删除失败");
                    }
                }

            })
            return
        }
    })
})

$(".container-fluid").on("click",".libraryConfirmBtn",function () {
    var content = '';
    var ListIndex = 1;
    $(this).parents(".submitBlock").siblings(".acctRuleWrap").find(".redCircle").each(function (index) {
        if (!$(this).hasClass("hide")) {
            content = $(this).parents(".choiceBox").siblings(".acctContent").children("span").html();
            ListIndex = index + 1
            return
        }
    })
    if ($(".acctRuleLiBrary").attr("type") == "elec") {
        $(".preview1").html("预览：结算电费=" + content);
        $("#div2").html($(".elecRuleLiBrary .elecRuleBtnWrap").find(".ruleBtnList" + ListIndex).html())
    } else if($(".acctRuleLiBrary").attr("type") == "service"){
        $(".preview2").html("预览：结算服务费=" + content);
        $("#div3").html($(".serviceRuleLiBrary .elecRuleBtnWrap").find(".ruleBtnList" + ListIndex).html())
    }
    var str = (content.replace(/\ +/g, "").split(""));
    var arr = []
    var patt1 = new RegExp("[\u4e00-\u9fa5]");
    var str1;
    for (var i = 0; i < str.length; i++) {
        console.log(str[i])
        if (patt1.test(str[i])) {
            str1 += str[i]
        } else {
            arr.push(str1);
            arr.push(str[i])
            str1 = ''
        }
    }
    console.log(arr)
    $(".acctRuleLiBrary").addClass("hide");
})

//编辑电费模板名称
$(".container-fluid").on("click","#editBtn",function () {
    // var ListIndex = 1;
    $(this).parents(".submitBlock").siblings(".acctRuleWrap").find(".redCircle").each(function (index) {
        if (!$(this).hasClass("hide")) {
            // ListIndex = index + 1;
            var ruleRepositoryId = $(this).parents(".acctRuleList").attr("attrId");
            // alert(ruleRepositoryId)
            var ruleName=$(this).parents(".acctRuleList").children(".title").html();
            // console.log(ruleName);
            $(".editAcctRuleModal").removeClass("hide").css("z-index",110);
            $(".editAcctRuleModal .ruleName").val(ruleName);
            $(".editAcctRuleModal .editNameConfirmBtn").unbind("click");
            $(".editAcctRuleModal .editNameConfirmBtn").click(function () {
                var editRuleName = $(".editAcctRuleModal .ruleName").val();
                if (editRuleName == "") {
                    alert("请填写规则名称");
                    return;
                }
                $.ajax({
                    "type": "POST",
                    "url": prefix + "/saveAcctRuleRepository",
                    "data": {
                        operatorStationId:$("#operatorStationId").val(),
                        tenantOperatorCode:$("#tenantOperatorCode").val(),
                        tenantCode:$("#tenantCode").val(),
                        ruleName : editRuleName,
                        ruleRepositoryId: ruleRepositoryId,
                    },
                    "success": function (data) {
                        if(data.status=="200"){
                            layer.msg("修改成功");
                            $(".editAcctRuleModal").addClass("hide");
                            listAcctRuleRepository('',"2")
                        }
                    }
                })
            })
            return
        }
    })
})

//编辑服务费费模板名称
$(".container-fluid").on("click","#serviceEditBtn",function () {
    // var ListIndex = 1;
    $(this).parents(".submitBlock").siblings(".acctRuleWrap").find(".redCircle").each(function (index) {
        if (!$(this).hasClass("hide")) {
            // ListIndex = index + 1;
            var ruleRepositoryId = $(this).parents(".acctRuleList").attr("attrId");
            var ruleName=$(this).parents(".acctRuleList").children(".title").html();
            $(".editAcctRuleModal").removeClass("hide").css("z-index",110);
            $(".editAcctRuleModal .ruleName").val(ruleName);
            $(".editAcctRuleModal .editNameConfirmBtn").unbind("click");
            $(".editAcctRuleModal .editNameConfirmBtn").click(function () {
                var editRuleName = $(".editAcctRuleModal .ruleName").val();
                if (editRuleName == "") {
                    alert("请填写规则名称");
                    return;
                }
                $.ajax({
                    "type": "POST",
                    "url": prefix + "/saveAcctRuleRepository",
                    "data": {
                        operatorStationId:$("#operatorStationId").val(),
                        tenantOperatorCode:$("#tenantOperatorCode").val(),
                        tenantCode:$("#tenantCode").val(),
                        ruleName : editRuleName,
                        ruleRepositoryId: ruleRepositoryId,
                    },
                    "success": function (data) {
                        if(data.status=="200"){
                            layer.msg("修改成功");
                            $(".editAcctRuleModal").addClass("hide");
                            listAcctRuleRepository('',"2")//2代表刷新模板库
                        }
                    }
                })
            })
            return
        }
    })
})


function clearNoNum(obj) {
    obj.value = obj.value.replace(/[^\d.*(\-)]/g, "");  //清除“数字”和“.”以外的字符
    obj.value = obj.value.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的
    obj.value = obj.value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
    obj.value = obj.value.replace(/^(\-)*(\d+)\.(\d\d\d\d\d).*$/, '$1$2.$3');//只能输入两个小数
    // if (obj.value.indexOf(".") < 0 && obj.value != "") {//以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
    //     obj.value = parseFloat(obj.value);
    // }
}

//保存规则模板--命名
$(".nameConfirmBtn").click(function () {
    var ruleName = $(".ruleName").val();
    if ($(this).parents(".acctRuleModal").attr("type") == "elec") {
        var acctRule = $(".finalRule1").html().replace(/[\r\n]/g, "").replace(/\ +/g, "");
        var ruleType = "0"
    }else if($(this).parents(".acctRuleModal").attr("type") == "service"){
        var acctRule = $(".finalRule2").html().replace(/[\r\n]/g, "").replace(/\ +/g, "");
        var ruleType = "1"
    }else{
        return
    }
    if (ruleName == "") {
        alert("请填写规则名称");
        return;
    }
    $.ajax({
        "type": "POST",
        "url": prefix + "/saveAcctRuleRepository",
        "data": {
            operatorStationId:$("#operatorStationId").val(),
            tenantOperatorCode:$("#tenantOperatorCode").val(),
            tenantCode:$("#tenantCode").val(),
            ruleName : ruleName,
            acctRule : acctRule,
            ruleType : ruleType,
        },
        "success": function (data) {
            if(data.status=="200"){
                layer.msg("添加成功");
                $(".acctRuleNameModal").addClass("hide");
                listAcctRuleRepository('',"2")
            }
        }
    })
})
//保存规则模板--不命名
function saveAcctRuleRepository(index,ruleName){
    if (index == "1") {
        var acctRule = $(".finalRule1").html().replace(/[\r\n]/g, "").replace(/\ +/g, "");
        var ruleType = "0"
    }else if(index == "2"){
        var acctRule = $(".finalRule2").html().replace(/[\r\n]/g, "").replace(/\ +/g, "");
        var ruleType = "1"
    }
    $.ajax({
        "type": "POST",
        "url": prefix + "/saveAcctRuleRepository",
        "data": {
            operatorStationId:$("#operatorStationId").val(),
            tenantOperatorCode:$("#tenantOperatorCode").val(),
            tenantCode:$("#tenantCode").val(),
            ruleName : ruleName,
            acctRule : acctRule,
            ruleType : ruleType,
        },
        "success": function (data) {
            console.log(data);
            layer.msg("添加成功");
            listAcctRuleRepository('',"2")
        }
    })

}
//表单保存
$(".formConfirmBtn").click(function () {
    var acctRuleEndTime=$("#acctRuleEndTime").val();
    var preview1 = $(".preview1").html().replace(/[\r\n]/g, "").replace(/\ +/g, "");
    var preview2 = $(".preview2").html().replace(/[\r\n]/g, "").replace(/\ +/g, "");
    var remark = $(".remarkExplainBlock textarea").val();
    var acctDay = $(".acctDay").val();
    var halfMonthDay = $(".halfMonthDay").val();
    var runTime = $("#runTime").val();
    var ruleStartTime = $("#ruleStartTime").val();
    if (ruleStartTime<=acctRuleEndTime){
        alert("该时间段内存在进行中的规则,请重新设置");
        return;
    }
    var ruleEndTime = $("#ruleEndTime").val();
    // var data = "elecAcctRule=" + elecAcctRule + "&serviceAcctRule=" + serviceAcctRule + "&remark=" + remark + "&acctDay=" + acctDay + "&runTime=" + runTime + "&ruleStartTime=" + ruleStartTime + "&ruleEndTime=" + ruleEndTime;
    if (preview1 == "预览：结算电费=" && preview2 == "预览：结算服务费=") {
        alert("请填写结算规则");
        return;
    }
    if(preview1 !="预览：结算电费="){
        var testStr = '';
        var showStr = '';
        var resultStr = '';
        $(".drag_child1 .copyBtn").each(function () {
            if ($(this).hasClass("variable")) {
                testStr += "[" + $(this).text() + "]"
                showStr += $(this).text();
                resultStr += $(this).text();
            } else if ($(this).children().length > 0) {
                testStr += Math.abs(parseFloat($(this).children('input').val()));
                showStr += "("+$(this).children('input').val()+")";
                resultStr += $(this).children('input').val();
            } else {
                testStr += $(this).text();
                showStr += $(this).text();
                resultStr += $(this).text();
            }

        })
        if (testStr == "") {
            alert("结算规则为空");
            return;
        }
        if(!check(testStr, showStr, 1,"save",resultStr)){
            return
        }

    }
    if(preview2 !="预览：结算服务费="){
        var testStr = '';
        var showStr = '';
        var resultStr = '';
        $(".drag_child2 .copyBtn").each(function () {
            if ($(this).hasClass("variable")) {
                testStr += "[" + $(this).text() + "]"
                showStr += $(this).text();
                resultStr += $(this).text();
            } else if ($(this).children().length > 0) {
                testStr += Math.abs(parseFloat($(this).children('input').val()));
                showStr += "("+$(this).children('input').val()+")";
                resultStr += $(this).children('input').val();
            } else {
                testStr += $(this).text();
                showStr += $(this).text();
                resultStr += $(this).text();
            }
        })
        if (testStr == "") {
            alert("结算规则为空");
            return;
        }
        if(!check(testStr, showStr, 2,"save",resultStr)){
            return
        }

    }
    if($("#settlementMethod").val() !="2") {
        // alert($("#settlementMethod").val())
        if (acctDay == "" && halfMonthDay == "") {
            alert("请填写账单日");
            return;
        }
    }
    if (runTime == "") {
        alert("请选择账单生成时间");
        return;
    }
    if (ruleStartTime == "") {
        alert("请选择规则生效开始时间");
        return;
    }
    if (ruleEndTime == "") {
        alert("请选择规则生效结束时间");
        return;
    }
    var elecAcctRule = $(".finalRule1").html().replace(/[\r\n]/g, "").replace(/\ +/g, "");
    var serviceAcctRule = $(".finalRule2").html().replace(/[\r\n]/g, "").replace(/\ +/g, "");
    var gdkArr = []
    $(".new_model").each(function () {
        if($(this).find(".drag_child3").find("input").length>0){
            var ruleString = ($(this).find(".model_one").html()+$(this).find(".model_two").val()+"="+$(this).find(".drag_child3").text()+$(this).find(".drag_child3").find("input").val()).replace(/\s*/g,"");
            gdkArr.push(ruleString)
        }else{
            var ruleString = ($(this).find(".model_one").html()+$(this).find(".model_two").val()+"="+$(this).find(".drag_child3").text()).replace(/\s*/g,"");
            gdkArr.push(ruleString)
        }


    })
    gdkArr = gdkArr.join(",")
    $.ajax({
        "type": "POST",
        "url": prefix + "/saveAcctRule",
        "data": {
            "operatorStationId":$("#operatorStationId").val(),
            "tenantOperatorCode":$("#tenantOperatorCode").val(),
            "tenantCode":$("#tenantCode").val(),
            "elecAcctRule":elecAcctRule,
            "serviceAcctRule":serviceAcctRule,
            "acctRuleId":$("#acctRuleId").val(),
            "remark":remark,
            "acctDay":acctDay,
            "halfMonthDay":halfMonthDay,
            "runTime":runTime,
            "ruleStartTime":ruleStartTime,
            "ruleEndTime":ruleEndTime,
            "acctSubItems":gdkArr,
            "settlementMethod":$("#settlementMethod").val()
        },
        // "contentType":"application/json",
        "success": function (data) {
            if(data.status==200){
                layer.msg("操作成功");
                javascript:history.back(-1);
            }else{
                layer.msg(data.message);
            }
        }
    })
})


